#include <utils/mono-time.h>
#include <stdlib.h>
#include <stdio.h>

#define MTICKS_PER_SEC 10000000

#ifdef HOST_WIN32
#include <windows.h>

guint32 
mono_msec_ticks(void)
{
	return GetTickCount();
}

gint64
mono_100ns_ticks(void)
{
	static LARGE_INTEGER freq;
	LARGE_INTEGER value;

	if (!freq.QuadPart && !QueryPerformanceFrequency(&freq))
		return mono_100ns_datetime();
	QueryPerformanceCounter(&value);
	return value.QuadPart * MTICKS_PER_SEC / freq.QuadPart;
}

#define FILETIME_ADJUST ((guint64)504911232000000000LL)
gint64
mono_100ns_datetime(void)
{
	ULARGE_INTEGER ft;

	if (sizeof(ft) != sizeof(FILETIME))
		g_assert_not_reached();

	GetSystemTimeAsFileTime((FILETIME*)&ft);
	return FILETIME_ADJUST + ft.QuadPart;
}
#else

#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif

#if defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
#include <sys/param.h>
#include <sys/sysctl.h>
#endif

#include <time.h>

static gint64
get_boot_time(void)
{
#if defined(PLATFORM_MACOSX) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)
	int mib[2];
	size_t size;
	time_t now;
	struct timeval boottime;

	(void)time(&now);

	mib[0] = CTL_KERN;
	mib[1] = KERN_BOOTTIME;

	size = sizeof(boottime);

	if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1)
		return (gint64)((now - boottime.tv_sec) * MTICKS_PER_SEC);
#else
	FILE* uptime = fopen("/proc/uptime", "r");
	if (uptime)
	{
		double upt;
		if (fscanf(uptime, "%lf", &upt) == 1)
		{
			gint64 now = mono_100ns_ticks();
			fclose(uptime);
			return now - (gint64)(upt * MTICKS_PER_SEC);
		}
		fclose(uptime);
	}
#endif
	return (gint64)300 * MTICKS_PER_SEC;
}

guint32
mono_msec_ticks(void)
{
	static gint64 boot_time = 0;
	gint64 now;
	if (!boot_time)
		boot_time = get_boot_time();
	now = mono_100ns_ticks();
	return (now - boot_time) / 10000;
}

gint64
mono_100ns_ticks(void)
{
	struct timeval tv;
#ifdef CLOCK_MONOTONIC
	struct timespec tspec;
	static struct timespect tspec_freq = {0};
	static int can_use_clock = 0;
	if (!tspec_freq.tv_nsec)
	{
		can_use_clock = clock_getres(CLOCK_MONOTONIC, &tspec_freq) == 0;
	}
	if (can_use_clock)
	{
		if (clock_gettime(CLOCK_MONOTONIC, &tspec) == 0)
		{
			return ((gint64)tspec.tv_sec * MTICKS_PER_SEC + tspec.tv_nsec / 100);
		}
	}
#endif
	if (gettimeofday(&tv, NULL) == 0)
		return ((gint64)tv.tv_sec * 1000000 + tv.tv_usec) * 10;
	return 0;
}

#define EPOTH_ADJUST ((guint64)62135596800LL)

gint64
mono_100ns_datetime(void)
{
	struct timeval tv;
	if (gettimeofday(&tv, NULL) == 0)
		return (((gint64)tv.tv_sec + EPOTH_ADJUST) * 1000000 + tv.tv_usec) * 10;
}
#endif

